package com.bjpowernode.crm.settings.web.controller;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.bjpowernode.crm.commons.constant.AppConstants;
import com.bjpowernode.crm.commons.enums.RespCode;
import com.bjpowernode.crm.commons.resp.Result;
import com.bjpowernode.crm.settings.domain.User;
import com.bjpowernode.crm.settings.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.Objects;

/**
 * ClassName:
 * Package:com.bjpowernode.crm.settings.web.controller
 * author:郭鑫
 */
@Controller
public class UserController {

    @Autowired
    private UserService userService;

    @RequestMapping("/settings/qx/user/toLogin.do")
    public String toLogin() {
        return "settings/qx/user/login";
    }

    /**
     * 用户登录
     * @param request
     * @param loginAct
     * @param loginPwd
     * @return
     */
    @RequestMapping("/settings/qx/user/login.do")
    @ResponseBody
    public Object login(HttpServletRequest request,
                        @RequestParam("loginAct")String loginAct,
                        @RequestParam("loginPwd")String loginPwd){
        Result result = Result.ERROR();
        try {
            //用户登录：根据账号和密码查询用户信息
            //调用业务接口层中的方法
            User user = userService.login(loginAct,loginPwd);
            //1.若返回结果为空，则账号密码不匹配
            if(Objects.isNull(user)){
                result.setRespCode(RespCode.ACT_PWD_NOT_MATCHED);
                return result;
            }
            //2.验证当前账号是否过期
            if (StrUtil.isNotBlank(user.getExpireTime()) && DateUtil.compare(new Date(), DateUtil.parse(user.getExpireTime(), "yyyy-MM-dd HH:mm:ss")) >= 0) {
                result.setRespCode(RespCode.ACT_STATUS_EXPIRED);
                return result;
            }
            //3.验证当前账号是否锁定
            if (StrUtil.isNotBlank(user.getLockState()) && StrUtil.equals("0", user.getLockState())) {
                result.setRespCode(RespCode.ACT_LOCKED);
                return result;
            }
            //4.验证当前IP是否允许登录
            //获取访问的IP地址
            String remoteHost = request.getRemoteHost();
            if (StrUtil.isNotBlank(user.getAllowIps()) && !user.getAllowIps().contains(remoteHost)) {
                result.setRespCode(RespCode.IP_NOT_ALLOW);
                return result;
            }


            //将用户信息放到session中
            request.getSession().setAttribute(AppConstants.SESSION_USER,user);
            result = Result.SUCCESS();
        } catch (Exception e) {
            e.printStackTrace();
            return result;
        }
        return result;
    }
}
